
import UIKit
class TF_CourseDownLoadRoot: UIView , UITableViewDelegate, UITableViewDataSource,TFdocDownloaderManagerDelegate {
    

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.dataSource.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableview.dequeueReusableCell(withIdentifier: "courseCell") as! TF_CourseDownloadCell
        cell.cellwidth = self.frame.size.width
        cell.controlBtn.tag = indexPath.row;
        cell.type = self.type
        cell.dataArr = self.dataSource;
        cell.controlBtn.addTarget(self, action: #selector(startCourseDown(_:)), for: .touchUpInside)
        let model = self.dataSource[indexPath.row] as! TFdoc
        self.updateUI(model, cell: cell)
        cell.selectionStyle = .none;
        return cell
    }
    
   
    func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCell.EditingStyle {
        if self.tableview.isEditing {

            return .insert
        }else{
            return .delete
        }
    }
    func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
        if (editingStyle == UITableViewCell.EditingStyle.delete) {
            //数据库删除
            let model: TFdoc = self.dataSource[indexPath.row] as! TFdoc
           
            self.manager.deleteDocDownloader(model)
            
            if self.dataSource.count > indexPath.row {
                self.dataSource.removeObject(at: indexPath.row)

              
            }
            
            if self.dataSource.count > 0 {
                self.noliveLab.isHidden = true
                self.noLiveImg.isHidden = true
            } else {
                self.noliveLab.isHidden = false
                self.noLiveImg.isHidden = false
            }
            
            self.tableview.reloadData()
        }
           
    }
    //是否可以编辑  默认YES
    func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        if self.isEdit {
            return true
        } else {
            return false
        }
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if self.delegate != nil && (self.delegate?.responds(to: #selector(TF_CourseDownLoadDetailDelegate.checkCourseDetail(_:))))!{
            let model = self.dataSource[indexPath.row] as! TFdoc
            self.delegate?.checkCourseDetail(model)
        }

        
    
    }
    
    @objc public var type:ClassLive = .small
    var dataSource:NSMutableArray = NSMutableArray.init()
    var tableview:UITableView!
    @objc public var isEdit:Bool = false
    @objc public weak var delegate : TF_CourseDownLoadDetailDelegate?
    @objc public var manager = TFdocDownloaderManager.share() as! TFdocDownloaderManager


    //保存读取的在线课件数据
//    @objc public var arr = NSMutableArray.init()
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.tableview = UITableView.init(frame: .zero)
        self.tableview.delegate = self
        self.tableview.dataSource = self
        self.tableview.backgroundColor = UIColor.clear
        self.tableview.separatorStyle = .none
        addSubview(self.tableview)
        self.tableview.register(TF_CourseDownloadCell.self, forCellReuseIdentifier: "courseCell")
        self.tableview.rowHeight = 90;
        
        addSubview(self.noLiveImg)
        addSubview(self.noliveLab)
        
        self.manager.delegate = self
    }
    

    //更新数据
  func upCourseDownloadData(_ arr:[TFdoc]) {
        self.dataSource.removeAllObjects()
        self.dataSource.addObjects(from: arr)
       if self.dataSource.count > 0 {
           self.noliveLab.isHidden = true
           self.noLiveImg.isHidden = true
       } else {
           self.noliveLab.isHidden = false
           self.noLiveImg.isHidden = false
       }
        self.tableview.reloadData()
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        self.tableview.frame = self.bounds;
      
        self.noLiveImg.frame = CGRect(x: (self.bounds.size.width - 132 ) / 2.0, y: self.frame.size.height/3.0-40, width: 132, height: 84)
        self.noliveLab.frame = CGRect(x: (self.bounds.size.width - 200 ) / 2.0, y: self.noLiveImg.frame.maxY + 16, width: 200, height: 24)
    }
    
   
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    lazy var noLiveImg:UIImageView = {
        let img = UIImageView.init()
        img.image = UIImage.init(named: "HTLive.bundle/wukejianque")
        return img
    }();
    lazy var noliveLab:UILabel = {
        let lab = UILabel.init()
        lab.font = UIFont.PingFang(size: 17)
        lab.text = "暂无课件";
        lab.textColor = UIColor(red: 110/255.0, green: 112/255.0, blue: 113/255.0, alpha: 1.0)
        lab.textAlignment = .center
        return lab
    }()
    
    @objc func startCourseDown(_ btn:TalkfunIncreaseButton)  {
        let t = btn.tag
        if self.dataSource.count > 0 {
            let model =  self.dataSource[t] as! TFdoc;
            if model.status == TFCourseDownloadStatusStart  {
                //暂停下载
                self.manager.pauseDocDownloader(model)
            }else if model.status == TFCourseDownloadStatusPrepare  {
            
                self.manager.pauseDocDownloader(model)
            }
            else {
                // 开始下载
                self.manager.startDocDownloader(model)
            }
        }
    }
    // MARK: - 模型状态更新
    func docDownloaderStatusUpdate(_ model: TFdoc) {
   
            for i in stride(from: 0, to: self.dataSource.count ,by: 1) {
                let mod = self.dataSource[i] as! TFdoc
                if mod.id == model.id {
                    self.dataSource .replaceObject(at: i, with: model)
                    break
                }
            }
            let visibleCells =  self.tableview.visibleCells
 
            for i in stride(from: 0, to: visibleCells.count ,by: 1) {
                  
                let cell = visibleCells[i] as! TF_CourseDownloadCell
              
                if cell.IDs == model.id {
                    
                    self.updateUI(model, cell: cell)
                    
                }
          
           }
        
       
    
    }

    
    func StringToFloat(str:String)->(CGFloat){


            let string = str

            var cgFloat:CGFloat = 0

            if let doubleValue = Double(string)

            {

                cgFloat = CGFloat(doubleValue)

            }

            return cgFloat

     }
    
    
    @objc public func setCourseDownManagerdelegate()
    {
        self.manager.delegate = self
    }
    
    @objc public func getCourseDownData(_ param:TFdocParam)
    
    {
        self.manager.getCourseDocumentList(param) {[weak self] (code, arr, error) in
            
            guard let `self` = self else { return }
            if (code == 0) {
                self.upCourseDown(list: arr)
             
            } else {
                self.TF_toast( error!.msg)
              
            }
            
        }

        
        
    }
    
    @objc public func upCourseDown(list:NSArray)
    {

        self.upCourseDownloadData(list as! [TFdoc])
    }
    
    func updateUI(_ model:TFdoc ,cell:TF_CourseDownloadCell) {

        cell.IDs = model.id
        if cell.type == .small {
            cell.backgroundColor = UIColor(red: 49/255.0, green: 52/255.0, blue: 57/255.0, alpha: 1.0)
            cell.courseTitle.textColor = UIColor.white
            cell.coursePage.textColor = UIColor(red: 184/255.0, green: 189/255.0, blue: 196/255.0, alpha: 1.0)
            cell.courseTotal.textColor = UIColor(red: 184/255.0, green: 189/255.0, blue: 196/255.0, alpha: 1.0)
            cell.progressViewLine.backgroundColor = UIColor(red: 0.35, green: 0.4, blue: 0.44, alpha: 1)
            cell.controlBtn.setTitleColor(UIColor(red: 0.45, green: 0.47, blue: 0.52,alpha:1), for: .normal)
        } else {
            cell.backgroundColor = UIColor.white
            cell.courseTitle.textColor = UIColor(red: 20/255.0, green: 23/255.0, blue: 26/255.0, alpha: 1.0)
            cell.coursePage.textColor = UIColor(red: 99/255.0, green: 104/255.0, blue: 109/255.0, alpha: 1.0)
            cell.courseTotal.textColor = UIColor(red: 99/255.0, green: 104/255.0, blue: 109/255.0, alpha: 1.0)
            cell.progressViewLine.backgroundColor = UIColor(red: 0.85, green: 0.88, blue: 0.91, alpha: 1)
            cell.controlBtn.setTitleColor(UIColor(red: 0.47, green: 0.48, blue: 0.5,alpha:1), for: .normal)
        }
        
   
        cell.courseTotal.text = model.size;
        
       
        cell.coursePage.text = model.pages + "页"
        
    
        cell.courseTitle.text = model.name;
        cell.imgType.text = model.ext;
        let courseImgStr:NSString = model.thumbnail as NSString
        let courseImgURL = NSURL.init(string: courseImgStr as String)
        cell.courseImg.sd_setImage(with: courseImgURL as URL?, completed: nil)
        
        cell.courseImg.frame = CGRect(x: 16, y: 12, width: 98, height: 66)
        cell.imgType.frame = CGRect(x: 0, y: 0, width: 30, height: 14)
       
        cell.courseTitle.frame = CGRect(x: cell.courseImg.frame.maxX+8, y: 12, width: cell.cellwidth-80-cell.courseImg.frame.maxX-8, height: 20)
     
        cell.getMaskLayer(rect: cell.imgType.bounds)
        cell.imgType.layer.mask = cell.maskLayer;
        cell.coursePage.frame = CGRect(x: cell.courseImg.frame.maxX+8, y: cell.courseTitle.frame.maxY+29.5, width: 40, height: 16.5)
        cell.courseTotal.frame = CGRect(x: cell.coursePage.frame.maxX, y: cell.courseTitle.frame.maxY+29.5, width: 60, height: 16.5)
     
        
        if model.ext == "png" {
            cell.imgType.backgroundColor = UIColor(red: 255/255.0, green: 121/255.0, blue: 32/255.0, alpha: 1.0)
        } else if (model.ext == "docx") {
            cell.imgType.backgroundColor = UIColor(red: 0/255.0, green: 185/255.0, blue: 255/255.0, alpha: 1.0)
        } else if(model.ext == "pptx") {
            cell.imgType.backgroundColor = UIColor(red: 239/255.0, green: 64/255.0, blue: 64/255.0, alpha: 1.0)
        } else if (model.ext == "pdf") {
            cell.imgType.backgroundColor = UIColor(red: 255/255.0, green: 121/255.0, blue: 32/255.0, alpha: 1.0)
        }

        cell.coursePage.frame = CGRect(x: cell.courseImg.frame.maxX+8, y: cell.courseTitle.frame.maxY+11.5, width: 40, height: 16.5)
        cell.courseTotal.frame = CGRect(x: cell.coursePage.frame.maxX, y: cell.courseTitle.frame.maxY+11.5, width: 60, height: 16.5)
        
        let f1:CGFloat = model.tmpSize / 1024.0 / 1024.0
        let f2:CGFloat = model.sizeBytes / 1024.0 / 1024.0
        let f3 = f1/f2*100.0
        let f4 = NSString.init(format: "%f", f3).intValue
        cell.progressLab.text = "\(f4)" + "%"
        cell.progressViewLine.frame = CGRect(x: cell.courseImg.frame.maxX+8, y: cell.coursePage.frame.maxY+10, width: 144, height: 2)
        cell.progressLab.frame = CGRect(x: cell.progressViewLine.frame.maxX+4, y: cell.coursePage.frame.maxY+4, width: 25, height: 14)
        cell.progressView.frame = CGRect(x: 0, y: 0, width: f1/f2*cell.progressViewLine.frame.size.width, height: 2)
     
        if model.status == TFCourseDownloadStatusUnstart { //未开始
            cell.controlBtn.setImage(UIImage.init(named: "HTLive.bundle/CoursewareNotStarted"), for: UIControl.State.normal)
            cell.controlBtn.setTitle("", for: .normal);
            cell.downloadBtnLabel.isHidden  = true;
            cell.controlBtn.isEnabled =  true
            cell.progressViewLine.isHidden = true
            cell.progressLab.isHidden = true
        } else if (model.status == TFCourseDownloadStatusPrepare) { //下载准备
            cell.controlBtn.setImage(UIImage.init(named: "HTLive.bundle/waitque_moren"), for: UIControl.State.normal)
            cell.controlBtn.setTitle("", for: .normal);
            cell.downloadBtnLabel.isHidden  = true;
            cell.controlBtn.isEnabled =  true
            cell.progressViewLine.isHidden = true
            cell.progressLab.isHidden = true
//            print("等待队列_默认");
        } else if (model.status == TFCourseDownloadStatusFinish) { //下载完成
            cell.controlBtn.isEnabled = false
            cell.controlBtn.setImage(UIImage.init(named: "HTLive.bundle/"), for: UIControl.State.normal)
            cell.controlBtn.setTitle("已下载", for: .normal)
            cell.controlBtn.titleLabel?.font = UIFont.PingFang(size: 12)
          
            cell.downloadBtnLabel.isHidden = true
            cell.progressViewLine.isHidden = true
            cell.progressLab.isHidden = true

        } else if (model.status == TFCourseDownloadStatusStart) { // 下载开始
            cell.controlBtn.setImage(UIImage.init(named: "HTLive.bundle/kejiannow"), for: UIControl.State.normal)
            cell.controlBtn.setTitle("", for: .normal);
            cell.downloadBtnLabel.isHidden = true
            cell.controlBtn.isEnabled = true

            cell.progressViewLine.isHidden = false;
            cell.progressLab.isHidden = false;


            cell.progressView.backgroundColor = UIColor(red: 0.25, green: 0.59, blue: 0.92, alpha: 1)
            cell.progressLab.textColor = UIColor(red: 0.25, green: 0.59, blue: 0.92,alpha:1)
            
//            print("课件正在下载=====>");
        } else if (model.status == TFCourseDownloadStatusError) { // 下载失败
            cell.controlBtn.setImage(UIImage.init(named: "HTLive.bundle/CoursewareNotStarted"), for: UIControl.State.normal)
            cell.controlBtn.setTitle("", for: .normal);
            cell.downloadBtnLabel.isHidden = false
            cell.controlBtn.isEnabled = true
            cell.progressViewLine.isHidden = true;
            cell.progressLab.isHidden = true
        } else if (model.status == TFCourseDownloadStatusPause) { //下载暂停
//            print("下载暂停");
                cell.controlBtn.setImage(UIImage.init(named: "HTLive.bundle/kejianstop"), for: UIControl.State.normal)
            cell.controlBtn.setTitle("", for: .normal);
            cell.downloadBtnLabel.isHidden = true
            cell.controlBtn.isEnabled = true
            cell.progressViewLine.isHidden = false;
            cell.progressLab.isHidden = false;
            
            
            cell.progressLab.textColor = UIColor(red: 0.59, green: 0.63, blue: 0.67,alpha:1)
            if cell.type == .small {
                cell.progressView.backgroundColor = UIColor(red: 0.49, green: 0.55, blue: 0.61, alpha: 1)
            } else {
                cell.progressView.backgroundColor = UIColor(red: 0.75, green: 0.8, blue: 0.85, alpha: 1)
            }
         
        }
    }
    
}

@objc protocol TF_CourseDownLoadDetailDelegate : NSObjectProtocol {
    //查看课件详情
    func checkCourseDetail(_ model:TFdoc)
    
}

